package
{
	import com.bit101.components.HUISlider;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class Example extends Sprite
	{
		public var speed : Number = 10;
		public var gravity : Number = 0;
			
		public var ball : Sprite = new Sprite();
		public var stageRect : Rectangle;
		public var vel : Point = new Point(1,1);	
		
		public function Example()
		{
			if( stage ) init();
			else addEventListener( Event.ADDED_TO_STAGE, handleAddedToStage );
			
			var cb : ControlBoard = new ControlBoard( this );
			cb.attachControlToProperty( this, 'speed', cb.huislider2, true );
			cb.attachControlToProperty( this, 'gravity', cb.huislider3, true );
		}
		
		protected function init():void
		{
			setStageRect();
			addEventListener(Event.ENTER_FRAME,handleEnterFrame);
			stage.addEventListener(Event.RESIZE,handleResize);
			
			ball.graphics.beginFill(0xff0000);
			ball.graphics.drawCircle(0,0,5);
			ball.graphics.endFill();
			
			addChild(ball);

		}
		
		protected function setStageRect():void
		{
			stageRect = new Rectangle(0,0,stage.stageWidth,stage.stageHeight);
			ball.x = stageRect.width * .5;
			ball.y = stageRect.height * .5;
		}
		
		protected function handleEnterFrame(e:Event):void
		{
			vel.normalize( speed );
			vel.y += gravity;
			ball.x += vel.x;
			ball.y += vel.y;
			var collisionx : Boolean = false;
			var collisiony : Boolean = false;
			if( collisionx = ball.x > stageRect.width ) ball.x = stageRect.width;
			else if( collisiony = ball.y > stageRect.height ) ball.y = stageRect.height;
			else if( collisionx = ball.x < 0 ) ball.x = 0;
			else if( collisiony = ball.y < 0 ) ball.y = 0;
			
			if( collisionx ) vel.x = -vel.x;
			if( collisiony ) vel.y = -vel.y;
			
			
		}
		
		protected function handleAddedToStage(e:Event):void
		{
			init();			
		}
		
		protected function handleResize(e:Event):void
		{
			setStageRect();
		}
	}
}